<template>
  <el-upload
    class="column"
    style="margin-top: 12px"
    :accept="fileAccept"
    :action="upload_url"
    :headers="headers"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-success="uploadSuccess"
    :before-remove="beforeRemove"
    :on-remove="removeFile"
    :on-preview="previewFile"
    :disabled="downloadOnly"
  >
    <el-button v-show="!downloadOnly" slot="trigger" size="middle" type="text">上传附件</el-button>
  </el-upload>
</template>

<script>
import {
  cloneDeep
} from 'lodash'
import axios from 'axios'
import {
  getToken
} from '@/utils/auth'
import {
  WEBAPI,
  PREAPI,
  PROXY
} from '@/settings'
import {
  getUploadUrl,
  removeFile
} from '@/api/upload.js'
export default {
  props: {
    fileAccept: {
      type: String,
      default: 'image/*,audio/*,video/*,text/plain,application/pdf,application/rtf,application/ogg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel.addin.macroEnabled.12,application/vnd.ms-excel.sheet.binary.macroEnabled.12,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.ms-works,application/vnd.ms-project,application/vnd.openxmlformats-officedocument.presentationml.slide,application/vnd.ms-asf,.zip,.7z,.rar'
    },
    ltSize: {
      type: Number,
      default: 10
    },
    downloadOnly: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      upload_url: '',
      headers: {}
    }
  },
  created() {
    this.headers = {
      Authorization: getToken()
    }
    this.upload_url = getUploadUrl()
  },
  methods: {
    beforeUpload(file) {
      const isLtSize = file.size / 1024 / 1024 < this.$props.ltSize
      if (!isLtSize) {
        this.$message.error('上传文件不能超过 ' + this.$props.ltSize + 'MB!')
      }
      return isLtSize
    },
    uploadSuccess(response, file, fileList) {
      this.fileList.push(file)
      this.$emit('update:fileList', this.fileList)
    },
    beforeRemove(file, fileList) {
      if (this.$props.downloadOnly) {
        this.$message.error('不允许删除文件!')
        return false
      }
    },
    removeFile(file, fileList) {
      const _this = this
      removeFile(file.response.data.upload_name).then(res => {
        _this.$emit('update:fileList', this.fileList)
      })
    },
    previewFile(file) {
      this.myDownloadFile(file.response.data.upload_name, file.response.data.origin_name)
    },
    myDownloadFile(upload_name, origin_name) {
      const service = axios.create({
        proxy: PROXY,
        baseURL: PROXY ? PREAPI : WEBAPI + PREAPI, // url = base url + request url
        withCredentials: true, // send cookies when cross-domain requests
        timeout: 10 * 1000 // request timeout
      })
      service.get('/file/download', {
        params: {
          fileName: upload_name
        },
        responseType: 'blob',
        headers: this.headers // 设置header信息
      }).then((res) => {
        const blob = new Blob([res.data]) // 构造一个blob对象来处理数据

        // IE10以上
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, origin_name)
          return
        }
        // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = origin_name // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        }
      }).catch((err) => {
        console.log(err)
      })
    }
  }
}
</script>

<style>
.upload-demo {
  width: 360px;
  margin: 20px;
}
</style>
